package org.scaffold.config;

import org.scaffold.jdbc.DbHandle;
import org.scaffold.jdbc.TableInfo;
import org.scaffold.utils.LogUtils;
import org.scaffold.velocity.TemplateUtils;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;

/**
 * 实体类生成器助手
 */
public class DomainOptionConfigHandle extends GeneratorOptionConfigHandle {

    @Override
    public TableInfo builder(MybatisGenerateConfig generateConfig) throws SQLException {
        notNull(GenerateConfig.databaseUrl, "%s not null", "databaseUrl");
        notNull(GenerateConfig.generatePath, "%s not null", "generatePath");

        LogUtils.info("正在查询信息.....");

        DbHandle.DatabaseType databaseType = GenerateConfig.databaseUrl.contains(DbHandle.DatabaseType.MYSQL.name)
                ? DbHandle.DatabaseType.MYSQL : DbHandle.DatabaseType.ORACLE;
        if (DbHandle.DatabaseType.MYSQL == databaseType) {
            String[] generateDomain = getValue(generateConfig.generateDomain);
            TableInfo tableInfo = DbHandle.queryTableInfo(GenerateConfig.databaseUrl, generateDomain[1]);
            tableInfo.setPackageName(generateDomain[0]);
            return tableInfo;
        } else {
            //// TODO: 2016/11/21
        }
        return null;
    }

    @Override
    public void generate(MybatisGenerateConfig generateConfig) throws SQLException, IOException {
        TableInfo tableInfo = this.builder(generateConfig);
        TemplateUtils.doTemplate(tableInfo, GenerateConfig.generatePath, true, false, false, false, false);
        info("成功生成domain，保存路径：" + GenerateConfig.generatePath);
    }

    protected void info(String msg, Object... args) {
        System.out.println(String.format(msg, args));
    }

    protected void info(String msg) {
        System.out.println(msg);
    }

    protected String[] getValue(Map<String, String> map) {
        String key = map.keySet().iterator().next();
        String value = map.get(key);
        return new String[]{key, value};
    }

    protected void notNull(String databaseUrl, String mes, final Object... values) {
        if (databaseUrl == null || databaseUrl.trim().isEmpty()) {
            info(mes, values);
            throw new NullPointerException("");
        }
    }
}
